<template>
  <div class="createPost-container">
    <el-form v-if="!infoLoading" ref="postForm" :model="postForm" :rules="rules" class="form-container" label-width="100px">
      <div class="createPost-main-container">
        <el-row>
          <el-col v-if="!postForm.id" :span="4">
            <b>请选择接收用户</b>
            <el-tabs v-model="selectUserMode" @tab-click="tabChange">
              <el-tab-pane label="按部门选择" name="selectUserByDept">
                <el-input
                  v-model="filterText"
                  placeholder="输入关键字进行过滤"
                  style="margin:10px 0"
                />
                <el-tree
                  ref="tree"
                  show-checkbox
                  node-key="id"
                  :expand-on-click-node="false"
                  :data="treedata"
                  :filter-node-method="filterNode"
                />
              </el-tab-pane>
              <el-tab-pane label="按标签组选择" name="selectUserByGroup">
                <el-input
                  v-model="filterText2"
                  placeholder="输入关键字进行过滤"
                  style="margin:10px 0"
                />
                <el-tree
                  ref="tree2"
                  show-checkbox
                  node-key="id"
                  :expand-on-click-node="false"
                  :data="treedata2"
                  :filter-node-method="filterNode2"
                />
              </el-tab-pane>
            </el-tabs>
          </el-col>
          <el-col :span="20">
            <el-form-item style="margin-bottom: 40px;" prop="title" label="课程名称">
              <el-input v-model="postForm.title" />
            </el-form-item>
            <el-form-item style="margin-bottom: 40px;" prop="daterange" label="时间段">
              <el-date-picker
                v-model="postForm.daterange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
                @input="testClick"
              />
            </el-form-item>
            <el-form-item prop="content" style="margin-bottom: 30px;" label="课程简介">
              <Tinymce ref="editor" v-model="postForm.content" :height="400" />
            </el-form-item>
            <el-form-item style="margin-bottom: 30px;">
              <el-button type="primary" :loading="loading" @click="submitForm">保存</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </el-form>
  </div>
</template>

<script>
import Tinymce from '@/components/Tinymce'
const defaultForm = {
  id: null,
  userList: [],
  title: '', // 文章题目
  daterange: [],
  content: '' // 文章内容
}
export default {
  name: 'ArticleDetail',
  components: { Tinymce },
  props: {
    readOnly: {
      type: Boolean,
      default: false
    },
    infoid: {
      type: Number,
      default: 0
    },
    timestamp: {
      type: Number,
      default: 0
    }
  },
  data() {
    const validateRequire = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('必填项'))
      } else {
        callback()
      }
    }
    const validateRequire2 = (rule, value, callback) => {
      if (!value || value.length === 0) {
        callback(new Error('必填项'))
      } else {
        callback()
      }
    }
    return {
      selectUserMode: 'selectUserByDept',
      filterText: '',
      filterText2: '',
      treedata: [],
      treedata2: [],
      timestamp2: 0,
      dialogVisible: false,
      myHeaders: {},
      imageUrl: '',
      infoLoading: false,
      postForm: Object.assign({}, defaultForm),
      loading: false,
      deptOption: [],
      userOption: [],
      rules: {
        title: [{ validator: validateRequire }],
        content: [{ validator: validateRequire }],
        userList: [{ validator: validateRequire }],
        daterange: [{ validator: validateRequire2 }]
      },
      tempRoute: {},
      infoType: 0,
      checkedUser: []
    }
  },
  watch: {
    timestamp: {
      handler(val, oldVal) {
        if (this.$refs.tree) {
          this.$refs.tree.setCheckedKeys([0])
        }
        if (this.$refs.tree2) {
          this.$refs.tree2.setCheckedKeys([0])
        }
        console.log('val:' + val)
        this.getData(this.infoid)
      },
      immediate: true
    },
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  mounted() {
    this.myHeaders = {
      Authorization: 'Bearer ' + localStorage.getItem('token')
    }
    this.getDepts()
    this.getGroup()
    this.getUsers()
  },
  created() {
    // Why need to make a copy of this.$route here?
    // Because if you enter this page and quickly switch tag, may be in the execution of the setTagsViewTitle function, this.$route is no longer pointing to the current page
    // https://github.com/PanJiaChen/vue-element-admin/issues/1221
    this.tempRoute = Object.assign({}, this.$route)
  },
  methods: {
    tabChange() {
      console.log('tabChange')
      this.$refs.tree.setCheckedKeys([0])
      this.$refs.tree2.setCheckedKeys([0])
    },
    testClick(e) {
      console.log(e)
      // this.$nextTick(() => {
      //   this.postForm.daterange = null
      // })
      // this.postForm.daterange = e
      // this.postForm.daterange = null
      // this.$nextTick(() => {
      //   this.postForm.daterange = e
      //   this.$set(this.postForm, 'daterange', [e[0], e[1]])
      // })
    },
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    filterNode2(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    detail() {
      this.dialogVisible = true
      this.timestamp2 = new Date().getTime()
    },
    getDepts() {
      const para = {
        pageNum: 1,
        pageSize: 1000
      }
      this.$http
        .post('/api/sysDept/queryPage', para)
        .then(response => {
          if (response.data.success === true) {
            this.deptOption = []
            for (const item of response.data.result.records) {
              this.deptOption.push({ label: item.deptName, value: item.id })
              this.userOption.push({ label: item.deptName, options: [] })
              this.treedata.push({ id: item.id + 10000, label: item.deptName, children: [] })
            }
          } else {
            console.log('获取失败:' + response.data.message)
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    getGroup() {
      const para = {
        pageNum: 1,
        pageSize: 1000
      }
      this.$http
        .post('/api/busGroup/queryGroupByPage', para)
        .then(response => {
          if (response.data.success === true) {
            console.log('resultgroup')
            console.log(response.data.result.records)
            for (const item of response.data.result.records) {
              // 为了防止作为key的用户id重复，选择或取消时无法取消重复的id，将id前面增加标签组id_加以区分
              this.treedata2.push({ id: 'g_' + item.id, label: item.title, children: item.membersArray.map(it => ({ id: item.id + '_' + it.id, label: it.realName + '(' + it.deptName + ')' })) })
            }
          } else {
            console.log('获取失败:' + response.data.message)
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    getUsers() {
      const para = {
        pageNum: 1,
        pageSize: 1000
      }
      this.$http
        .post('/api/sysUser/queryUserPage', para)
        .then(response => {
          if (response.data.success === true) {
            for (const item of response.data.result.records) {
              if (item.deptName && item.deptName !== '') {
                const theDept = this.userOption.filter((p) => {
                  return p.label === item.deptName
                })
                theDept[0].options.push({ label: item.realName, value: item.id })
                const treeDept = this.treedata.find((p) => {
                  return p.label === item.deptName
                })
                if (item.sysRoleId !== 1) { treeDept.children.push({ label: item.realName, id: item.id }) }
              }
            }
            this.treedata = this.treedata.filter(item => item.children.length > 0)
          } else {
            console.log('获取失败:' + response.data.message)
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    getData(id) {
      console.log('id')
      console.log(id)
      if (id) {
        this.infoLoading = true
        this.$http
          .get('/api/busCourse/getDetailById?&id=' + id)
          .then(response => {
            this.infoLoading = false
            if (response.data.success === true) {
              this.postForm = response.data.result
              // this.postForm.daterange = [response.data.result.beginTime, response.data.result.endTime]
              this.$set(this.postForm, 'daterange', [response.data.result.beginTime, response.data.result.endTime])
              this.postForm.content = response.data.result.remark
            } else {
              console.log('获取失败:' + response.data.message)
              this.$message({
                message: '获取失败:' + response.data.message,
                type: 'error'
              })
            }
          })
          .catch(error => {
            console.log(error)
            this.infoLoading = false
          })
      } else {
        console.log('清空postForm')
        this.$nextTick(() => {
          this.infoLoading = false
          this.postForm = Object.assign({}, defaultForm)
          // this.$refs.editor.setContent('')
          if (this.$refs.editor) {
            this.$refs.editor.setContent('')
          }
        })
      }
    },
    add0(m) {
      return m < 10 ? '0' + m : m
    },
    submitForm() {
      this.$refs.postForm.validate(valid => {
        if (valid) {
          let para = {}
          if (this.postForm.id) {
            para = {
              id: this.postForm.id,
              title: this.postForm.title,
              published: this.postForm.published,
              remark: this.postForm.content,
              beginTime: this.postForm.daterange[0],
              endTime: this.postForm.daterange[1]
            }
          } else {
            let checkedUser = []
            if (this.selectUserMode === 'selectUserByDept') {
              checkedUser = this.$refs.tree.getCheckedKeys()
              if (!checkedUser || checkedUser.length === 0) {
                this.$message({
                  message: '至少选一个接收用户',
                  type: 'error'
                })
                return
              }
            } else if (this.selectUserMode === 'selectUserByGroup') {
              checkedUser = this.$refs.tree2.getCheckedKeys()
              if (!checkedUser || checkedUser.length === 0) {
                this.$message({
                  message: '至少选一个接收用户',
                  type: 'error'
                })
                return
              }
              // 先过滤掉id为g_开头的标签组节点，然后再把人员节点去掉_和_前面的标签组id
              checkedUser = checkedUser.filter(item => item.split('_')[0] !== 'g').map(item => item.split('_')[1])
            }
            // 去重
            checkedUser = [...new Set(checkedUser)]
            para = {
              id: this.postForm.id,
              title: this.postForm.title,
              remark: this.postForm.content,
              beginTime: this.postForm.daterange[0],
              endTime: this.postForm.daterange[1],
              userList: checkedUser.filter(item => item < 10000) // 去除部门id
            // deptIds: this.postForm.deptIds
            }
          }
          this.loading = true
          this.$http
            .post('/api/busCourse/saveCourse', para)
            .then(response => {
              this.loading = false
              if (response.data.success === true) {
                this.postForm.status = 'published'
                this.postForm = Object.assign({}, defaultForm)
                this.filterText = ''
                this.$message({
                  message: '提交成功',
                  type: 'success'
                })
                this.$emit('dialogHide')
              } else {
                console.log('提交失败:' + response.data.message)
                this.$message({
                  message: '提交失败:' + response.data.message,
                  type: 'error'
                })
              }
            })
            .catch(function(error) {
              console.log(error)
              this.loading = false
            })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";

.createPost-container {
  position: relative;

  .createPost-main-container {
    // padding: 40px 45px 20px 50px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
    }
  }

  .word-counter {
    width: 40px;
    position: absolute;
    right: 10px;
    top: 0px;
  }
}

.article-textarea ::v-deep {
  textarea {
    padding-right: 40px;
    resize: none;
    border: none;
    border-radius: 0px;
    border-bottom: 1px solid #bfcbd9;
  }
}
</style>
